package QuizUI;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.*;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import social.*;
import QuizPackage.Quiz;
import QuizPackage.QuizDBC;

/**
 * Servlet implementation class StartQuiz
 */
@WebServlet("/StartQuiz")
public class StartQuiz extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public StartQuiz() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher dispatch = request.getRequestDispatcher("StartQuiz.jsp");
		dispatch.forward(request,response);
		
		/*response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		out.println("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>");
		out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\""
				      + " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
		out.println("<html xmlns='http://www.w3.org/1999/xhtml'>");
		out.println("<head>");
		
		int quizid = Integer.parseInt(request.getParameter("quizid"));
		Quiz quiz = new Quiz(quizid);
		out.println("<title>"+quiz.getName()+"</title>");
		out.println("</head>");
		
		out.println("<body>");

		HttpSession session = request.getSession();
		session.setAttribute(request.getParameter("quizid"),quiz);

		out.println("<h1>"+quiz.getName()+"</h1>");
		out.println("<p>Click to start this quiz.</p>");
		out.println("<p>Description: "+quiz.getDescription()+"</p>");
		out.println("Creator: <a href=\"user-profile.jsp?profileName="+quiz.getCreator()+"\">"+quiz.getCreator()+"</a>");
		
		QuizDBC dbc = new QuizDBC();
		ResultSet rs = dbc.getQuiz(quizid);
		try {
			rs.next();
			out.println("<p>Category: "+rs.getString("category")+"</p>");
		} catch (SQLException e2) {
			e2.printStackTrace();
		}
		
		out.print("<p>Tags: ");
		rs = dbc.getTags(quizid);
		try {
			while(rs.next())
			{
				out.print("<a href=\"quizList.jsp?tag="+rs.getString("tag")+"\">"+rs.getString("tag")+"</a>  ");
				//out.print(rs.getString("tag")+",");
			}
		} catch (SQLException e2) {
			e2.printStackTrace();
		}
		out.println("</p>");
		
		
		out.println("<form action=\"QuestionServlet\" method=\"post\">");
		out.println("<input name=\"quizid\" type =\"hidden\" value=\""+quizid+"\"/>");
		out.println("<input type=\"submit\" value=\"Begin\">");
		out.println("</form>");

		
		out.println("</br></br>");
		out.println("Challenge a Friend!");
		out.println("<form action=\"ChallengeServlet\" method=\"post\">");
		out.println("<select name=\"friendName\">");
		
		SocialDBC db = (SocialDBC) getServletContext().getAttribute("database");
		String username = (String) session.getAttribute("username");

		ArrayList<String> friendList = db.getFriendList(username);
		for (int i=0; i<friendList.size(); i++) {
			String friendName = friendList.get(i);
			if (!db.challengeExists(friendName, username, quizid)) {
				out.println(String.format("<option value=\"%s\">%s</option>", friendName, friendName));
			}
		}
		
		out.println("</select>");
		out.println("<input type=\"submit\" value=\"Challenge\"/>");
		out.println("<input name=\"quizid\" type =\"hidden\" value=\""+quizid+"\"/>");
		out.println("</form>");
		
		rs = dbc.getResults(quizid);
		int totalScore=0;
		int numResults=0;
		int totalTime=0;
		int total=-1;
		try {
			while(rs.next())
			{
				totalScore += Integer.parseInt(rs.getString("score"));
				totalTime += Integer.parseInt(rs.getString("length"));
				numResults++;
				if(total==-1) total = Integer.parseInt(rs.getString("total"));
			}
		} catch (NumberFormatException e1) {
			e1.printStackTrace();
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		double averageScore = ((double)totalScore)/numResults;
		double averageTime = ((double)totalTime)/numResults;
		DecimalFormat df = new DecimalFormat("#.##");
		
		if(total!=-1)
		{
			out.println("<p>Average Score: "+df.format(averageScore)+"/"+total+"</p>");
			out.println("<p>Average Time: "+df.format(averageTime)+" seconds</p>");
		}else{
			out.println("<p>Average Score: -</p>");
			out.println("<p>Average Time: -</p>");
		}
		
		rs = dbc.getTopPerformers(quizid);
		out.println("<p>All Time Top Performers</p>");
		int count=0;
		try {
			while(rs.next() && count<5)
			{
				out.print("<a href=\"user-profile.jsp?profileName="+rs.getString("userID")+"\">"+rs.getString("userID")+"</a>");
				out.println(" Score="+rs.getString("score")+"/"+rs.getString("total")+"  Time="+rs.getString("length")+"</a><br/>");
				count++;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		rs = dbc.getTopPerformers(quizid);
		out.println("<p>Today's Top Performers</p>");
		count=0;
		Date date = new Date();
		long now = date.getTime();
		try {
			while(rs.next() && count<5)
			{
				if(Long.parseLong(rs.getString("timetaken")) > (now-Quiz.RECENT_TIME))
				{
					out.print("<a href=\"user-profile.jsp?profileName="+rs.getString("userID")+"\">"+rs.getString("userID")+"</a>");
					out.println(" Score="+rs.getString("score")+"/"+rs.getString("total")+"  Time="+rs.getString("length")+"</a><br/>");
					count++;
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		out.println("<p>Most recent results.</p>");
		rs = dbc.getResults(quizid);
		count = 0;
		try {
			while(rs.next() && count<5)
			{
				out.print("<a href=\"user-profile.jsp?profileName="+rs.getString("userID")+"\">"+rs.getString("userID")+"</a>");
				out.println(" Score="+rs.getString("score")+"/"+rs.getString("total")+"  Time="+rs.getString("length")+"</a><br/>");
				count++;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		out.println("</form>");
		out.println("</body>");
		out.println("</html>");*/
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
